package com.yhj.handler;

import com.yhj.vo.CommonResult;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.validation.ConstraintViolationException;

/**
 * @author yaohj
 * @date 2024年11月21日 14:57
 */
@Order(2)
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = {Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleAllExceptions(Exception ex) {
        if(ex instanceof ConstraintViolationException){
            logger.error("验证错误:"+ ex.getMessage());
        }
        // 记录日志，处理异常信息
        logger.error("全局错误:"+ ex.getMessage());
        return "An error occurred: " + ex.getMessage();
    }


    /**
     * 403 错误：权限不足
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(value = AccessDeniedException.class)
    public CommonResult handler(AccessDeniedException e) {
        logger.error("security权限不足：----------------"+ e.getMessage());
        return CommonResult.error(400, "权限不足");
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                                  HttpHeaders headers,
                                                                  HttpStatus status,
                                                                  WebRequest request) {
        logger.error("验证未通过:"+ ex.getMessage());
        // 记录日志，处理参数验证异常信息
        return new ResponseEntity<>("Validation failed: " + ex.getBindingResult().toString(), HttpStatus.BAD_REQUEST);
    }
}
